﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Data;
using System.Globalization;

namespace VietImageSoftware
{
    [ValueConversion(typeof(Binary), typeof(BitmapImage))]
    public class BitmapImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
                                                        CultureInfo culture)
        {
            Binary binary = value as Binary;
            if (binary != null)
            {
                using (var stream = new MemoryStream(binary.ToArray()))
                {
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource = stream;
                    bitmap.EndInit();
                    bitmap.Freeze();
                    return bitmap;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
                                                        CultureInfo culture)
        {
            BitmapImage bitmap = value as BitmapImage;
            Stream stream = bitmap.StreamSource;
            Byte[] buffer = null;
            if (stream != null && stream.Length > 0)
            {
                using (BinaryReader br = new BinaryReader(stream))
                {
                    buffer = br.ReadBytes((Int32)stream.Length);
                }
            }
            Binary bin = new Binary(buffer);
            return bin;
        }
    }
}
